package com.fjw.realm;

import com.fjw.pojo.User;
import com.fjw.service.PermissionService;
import com.fjw.service.RoleService;
import com.fjw.service.UserService;
import lombok.Data;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Set;

/**
 * @author fjw
 * @version 1.0
 * @date 2019/11/1 15:24
 */
@Data
public class MyRealm extends AuthorizingRealm {

    private UserService userService;
    private RoleService roleService;
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户名
        String Username = (String) principals.getPrimaryPrincipal();
        //根据用户名去查询权限和角色信息
        Set<String> role = roleService.findRoleByUsername(Username);
        Set<String> permission = permissionService.findPermissionByUsername(Username);
        //封装到一个对象中返回
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(role);
        simpleAuthorizationInfo.setStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //从token中获取用户输入的信息
        String UsernameOrEmail = (String) token.getPrincipal();
        //根据UsernameOrEmail去数据库查询看是否有用户
        User user = userService.login(UsernameOrEmail);
        //3.判断下user是否为空 如果为空返回null 交给后面的组件进行抛出异常
        if (user==null){
            return null;
        }
        //4.封装成AuthenticationInfo的一个子类 用户名 密码 盐 getName 后面交给密码比对器判断
        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());

    }
}
